package com.h3c.nem.config.mq.consumer;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.eos.common.util.IdWorker;
import com.h3c.nem.config.properties.EmailSendProperties;
import com.h3c.nem.constant.NemManageConstant;
import com.h3c.nem.entity.SdNoticeRecord;
import com.h3c.nem.entity.TbOfferWorker;
import com.h3c.nem.enums.OfferWorkerStatusEnum;
import com.h3c.nem.service.CommService;
import com.h3c.nem.service.ITbOfferWorkerService;
import com.h3c.nem.utils.BusiEnumDefine;
import com.h3c.nem.utils.EmailUtil;
import com.h3c.nem.utils.RedisUtil;
import com.rabbitmq.client.Channel;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 学历信息控制层
 *
 * @author chenyifan
 * @since 2022-06-20 11:42:52
 */
@Slf4j
@AllArgsConstructor
@Component
public class EsignAckReceiver implements ChannelAwareMessageListener {

    /**
     * 新员工侧签署中状态枚举
     */
    public static final Integer NEM_SIGNING_CODE = 7;
    /**
     * 新员工侧签署完成状态枚举
     */
    public static final Integer NEM_SIGN_SUCCESS_CODE = 8;
    /**
     * 新员工侧拒绝签署状态枚举
     */
    public static final Integer NEM_SIGN_REJECT_CODE = 11;
    /**
     * 新员工侧签署异常状态枚举
     */
    public static final Integer NEM_SIGN_FAIL_CODE = 55;

    public static final String ES_SIGN_MQ = NemManageConstant.PREFIX_COMMON_CACHE + "es:sendStatus:{}";


    private final ITbOfferWorkerService offerWorkerService;

    private final CommService commService;

    private final EmailSendProperties emailSendProperties;

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            JSONObject parseObj = JSONUtil.parseObj(message.getBody());
            String workerId = parseObj.getStr("workerId");
            Integer signStatus = parseObj.getInt("signStatus");
            if (signStatus.equals(NEM_SIGN_SUCCESS_CODE)) {
                if (!RedisUtil.setIfAbsent(StrUtil.format(ES_SIGN_MQ, workerId), "exist", 1, TimeUnit.HOURS)) {
                    channel.basicAck(deliveryTag, false);
                    return;
                }
                ThreadUtil.execute(() -> EmailUtil.sendPtEmail(emailSendProperties.getFinishSignTemplateCode(), null,
                        EmailUtil.getReceiveEmail(workerId, false, false, false, true),
                        "电子签署完成",null,null));
                //发送短信给预备员工
                String emailContent = EmailUtil.getEmailTemplateContent(emailSendProperties.getFinishSignTemplateCode(), null);
                SdNoticeRecord emailRecord = new SdNoticeRecord();
                emailRecord.setApplyUserId(commService.getLoginUserIdWithNoException());
                emailRecord.setNoticeType(BusiEnumDefine.NOTICE_TYPE_SMS);
                emailRecord.setTargetPhone(offerWorkerService.getById(workerId).getPhoneNo());
                emailRecord.setNoticeTitle("电子签署完成");
                emailRecord.setNoticeContent(emailContent);
                emailRecord.setCreateTime(new Date());
                emailRecord.setNoticeId(IdWorker.nextId() + "");
                commService.sendMessage(emailRecord);
            } else if (signStatus.equals(NEM_SIGN_REJECT_CODE)) {
                if (!RedisUtil.setIfAbsent(StrUtil.format(ES_SIGN_MQ, workerId), "exist", 1, TimeUnit.HOURS)) {
                    channel.basicAck(deliveryTag, false);
                    return;
                }
                HashMap<String, String> params = new HashMap<>(1);
                TbOfferWorker offerWorker = offerWorkerService.getById(workerId);
                if(Objects.isNull(offerWorker)){
                    channel.basicAck(deliveryTag, false);
                    return;
                }
                params.put("workerNameAndId",workerId.concat("/").concat(offerWorker.getWorkerName()));
                ThreadUtil.execute(() -> EmailUtil.sendPtEmail(emailSendProperties.getRejectSignTemplateCode(), params,
                        EmailUtil.getReceiveEmail(workerId, true, true, false, false),
                        "预备员工拒绝签署电子签",null,null));
            }
            offerWorkerService.update(null, new LambdaUpdateWrapper<TbOfferWorker>()
                    .set(TbOfferWorker::getWorkerStatus, OfferWorkerStatusEnum.valueOfKey(signStatus))
                    .eq(TbOfferWorker::getWorkerId, workerId)
            );
            channel.basicAck(deliveryTag, false);
            log.info("消费mq消息成功:{}", JSONUtil.parseObj(message.getBody()).toString());
        } catch (Exception e) {
            channel.basicReject(deliveryTag, false);
            //考虑记录消费不重发消息
            log.error("消息消费失败,消息内容:" + message.getBody() + ",失败原因:{}", e);
        }
    }

}
